package com.zzedu.web.controller.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zzedu.common.annotation.Log;
import com.zzedu.common.core.controller.BaseController;
import com.zzedu.common.core.domain.AjaxResult;
import com.zzedu.common.core.domain.entity.SysDept;
import com.zzedu.common.core.domain.entity.SysRole;
import com.zzedu.common.core.domain.entity.SysUser;
import com.zzedu.common.core.page.TableDataInfo;
import com.zzedu.common.core.text.Convert;
import com.zzedu.common.enums.BusinessType;
import com.zzedu.common.utils.poi.ExcelUtil;
import com.zzedu.system.domain.SysUserRole;
import com.zzedu.system.service.ISysDeptService;
import com.zzedu.system.service.ISysRoleService;
import com.zzedu.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色信息
 *
 * @author smarthome
 */
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @PreAuthorize("@permission.hasAnyPermissions('system:role:list')")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestBody SysRole role) {

        return getDataTable(roleService.selectRoleList(role));
    }

    @PreAuthorize("@permission.hasAnyPermissions('system:role:export')")
    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export( SysRole role) {
        List<SysRole> list = roleService.selectRoleList(role).getRecords();
        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
        return util.exportExcel(list, "角色数据");
    }


    @PreAuthorize("@permission.hasAnyPermissions('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @RequestMapping("/remove/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(roleService.removeBatchByIds(Arrays.stream(userIds).collect(Collectors.toList())));
    }
    /**
     * 新增保存角色
     */
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PreAuthorize("@permission.hasAnyPermissions('system:role:add')")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(@Validated @RequestBody SysRole role) {
        return toAjax(roleService.insertRole(role));
    }

    /**
     * 修改保存角色
     */
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @PreAuthorize("@permission.hasAnyPermissions('system:role:edit')")
    public AjaxResult edit(@Validated @RequestBody SysRole role) {
        return toAjax(roleService.updateRole(role));
    }

    /**
     * 角色状态修改
     */
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    @ResponseBody
    @PreAuthorize("@permission.hasAnyPermissions('system:role:edit')")
    public AjaxResult changeStatus(@RequestBody SysRole role) {
        return toAjax(roleService.updateRole(role));
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:role:query')")
    @RequestMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId) {
        roleService.checkRoleDataScope(roleId);
        return success(roleService.selectRoleById(roleId));
    }

    /**
     * 获取对应角色部门树列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:role:query')")
    @GetMapping(value = "/deptTree/{roleId}")
    public AjaxResult deptTree(@PathVariable("roleId") Long roleId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
        return ajax;
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @RequestMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getId());
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:role:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        return success(roleService.selectRoleAll());
    }


    /**
     * 查询已分配用户角色列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:role:list')")
    @RequestMapping("/authUser/allocatedList")
    public TableDataInfo allocatedList(@RequestBody SysUser user) {
        IPage<SysUser> page = userService.selectAllocatedList(user);
        return getDataTable(page);
    }


    /**
     * 查询未分配用户角色列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:role:list')")
    @RequestMapping("/authUser/unallocatedList")
    public TableDataInfo unallocatedList(@RequestBody SysUser user)
    {
        IPage<SysUser> page = userService.selectUnallocatedList(user);
        return getDataTable(page);
    }


    /**
     * 取消授权用户
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @RequestMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole)
    {
        return toAjax(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权用户
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @RequestMapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long id, String userIds)
    {
        return toAjax(roleService.deleteAuthUsers(id, Convert.toLongArray(userIds)));
    }
    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@permission.hasAnyPermissions('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @RequestMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long id, String userIds)
    {
        roleService.checkRoleDataScope(id);
        return toAjax(roleService.insertAuthUsers(id, Convert.toLongArray(userIds)));
    }
}